package user

import (
	"gitee.com/xiaoyutab/gatway/config"
	"gitee.com/xiaoyutab/gatway/model"
	"gitee.com/xiaoyutab/xgotool/optional/xcache"
	"gitee.com/xiaoyutab/xgotool/xerror"
)

// 获取用户详情
//
//	id	用户ID
func GetInfoById(id uint) (*model.User, error) {
	if id <= 0 {
		return nil, xerror.New("用户ID获取错误")
	}
	info := model.User{}
	cache_key := xcache.Key("service.user.get.info.by.id", id)
	if xcache.Exists(cache_key) {
		if err := xcache.GetStruct(cache_key, &info); err == nil {
			return &info, nil
		}
	}
	// 连接数据库进行查询
	err := config.DB.Table(info.TableName()).Where("id", id).Find(&info).Error
	if err != nil {
		return nil, xerror.To(err)
	}
	if info.Id <= 0 {
		return nil, xerror.New("用户未找到")
	}
	xcache.SetStruct(cache_key, info)
	xcache.SetStruct(xcache.Key("service.user.get.info.by.username", info.Username), info)
	return &info, nil
}
